package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.tanhua.domain.mongo.Video;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class VideoMQService {

    @Reference
    private VideoApi videoApi;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 发布视频
     */
    public void videoMsg(String videoId) {
        this.sendMsg(videoId, 1);
    }


    /**
     * 对视频点赞
     */
    public void likeVideoMsg(String videoId) {
        this.sendMsg(videoId, 2);
    }

    /**
     * 取消视频点赞
     */
    public void disLikeVideoMsg(String videoId) {
        this.sendMsg(videoId, 3);
    }

    /**
     * 评论视频
     */
    public void commentVideoMsg(String videoId) {
        this.sendMsg(videoId, 4);
    }

    private void sendMsg(String videoId, Integer type){

        try {
            Video video = videoApi.findById(videoId);

            Map<String, Object> map = new HashMap<>();

            map.put("videoId", videoId);
            map.put("userId", UserHolder.getUserId());
            map.put("type",type);
            map.put("vid", video.getVid());

            rocketMQTemplate.convertAndSend("tanhua-video", JSON.toJSONString(map));
        } catch (MessagingException e) {
            log.info("发送失败，出现错误！");
            log.info("发送失败，错误为：" + e);
        }
    }
}
